package com.service.totalauth.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.service.config.constant.ApiUrlConstants;
import com.service.config.dto.SiteDto;
import com.service.config.utils.JsonXMLUtils;
import com.service.config.utils.RedisUtil;
import com.service.totalauth.dto.TokenIdDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

/**
 * @program: CloudCampusService
 * @description: 云管理Api封装
 * @author: rui
 * @create: 2021-03-31 14:26
 **/

@Component
@Slf4j
public class CloudCampusApi implements ApiUrlConstants {

    @Resource
    RestTemplate restTemplate;
    @Resource
    RedisUtil redisUtil;
    /**
     * 校验账号
     * @param username
     * @param password
     * @param requestHeaders
     * @return
     */
    public TokenIdDto getToken1(String username, String password, HttpHeaders requestHeaders, String domain) {
        //获取token
        Map map = new HashMap();
        map.put("userName", username);
        map.put("password", password);
        try {
            HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
            StringBuilder stringBuilder = new StringBuilder();
            if (domain.equals("global")){
                log.info("global--{}",CLOUD_CAMPUS_TOKEN_URL_NOT);
                stringBuilder.append(URL_FIRST).append(domain).append(CLOUD_CAMPUS_TOKEN_URL_NOT);
            }else if (domain.equals("cn1")){
                log.info("cn1--{}",CT_YUN_CLOUD_CAMPUS_TOKEN_URL);
                stringBuilder.append(URL_FIRST).append(CT_YUN_CLOUD_CAMPUS_TOKEN_URL);
            }else if (domain.equals("cn2")){
                log.info("cn2--{}",CN2_CLOUD_CAMPUS_TOKEN_URL);
                stringBuilder.append(URL_FIRST).append(CN2_CLOUD_CAMPUS_TOKEN_URL);
            }
            ResponseEntity<JSONObject> response = restTemplate.exchange(stringBuilder.toString(), HttpMethod.POST, requestEntity, JSONObject.class);
            TokenIdDto data = response.getBody().getJSONObject("data").toJavaObject(TokenIdDto.class);
            log.info("data--->{}", JsonXMLUtils.obj2json(data));
            return data;
        } catch (Exception e) {
            log.error("debug Token ==>" + e.getMessage());
            return null;
        }
    }
    /**
     * 根据缓存获取token_id
     * @param username
     * @param password
     * @param requestHeaders
     * @return
     */
    public HttpHeaders getTokenRedis(String username, String password,String domain, HttpHeaders requestHeaders) {
        String token = "";
        log.info("----"+username.concat("token"));
        if (redisUtil.exist(username.concat("token"))) {
            log.info("---------");
            token = redisUtil.getValue(username.concat("token"));
            requestHeaders.add("X-AUTH-TOKEN", token);
            requestHeaders.add("Accept-Language", "en-US");
            return requestHeaders;
        } else {
            try {
                log.info("+++++++++++");
                Map map = new HashMap(16);
                map.put("userName", username);
                map.put("password", password);
                HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
                StringBuilder stringBuilder = new StringBuilder();
                if (domain.contains("global")){
                    stringBuilder.append(URL_FIRST).append(domain).append(CLOUD_CAMPUS_TOKEN_URL_NOT);
                }else if (domain.contains("cn1")){
                    stringBuilder.append(URL_FIRST).append(CT_YUN_CLOUD_CAMPUS_TOKEN_URL);
                }else if (domain.contains("cn2")){
                    stringBuilder.append(URL_FIRST).append(CN2_CLOUD_CAMPUS_TOKEN_URL);
                }
                ResponseEntity<JSONObject> response = restTemplate.exchange(stringBuilder.toString(), HttpMethod.POST, requestEntity, JSONObject.class);
                JSONObject jsonObject = Objects.requireNonNull(response.getBody()).getJSONObject("data");
                token = jsonObject.get("token_id").toString();
                log.info("token-->{}",token);
                redisUtil.set(username.concat("token"), 1, token, 10);
                requestHeaders.add("X-AUTH-TOKEN", token);
                requestHeaders.add("Accept-Language", "en-US");
                return requestHeaders;
            } catch (Exception e) {
                return null;
            }
        }
    }
    /**
     * 获取站点site
     *
     * @param requestHeaders
     * @return
     */
    public List<SiteDto> getSites(HttpHeaders requestHeaders, String domain) {
        //获取站点
        int pageIndex = 1;
        List<SiteDto> siteDtos = new ArrayList<>();
        boolean flag = true;
        try {
            while (flag) {
                HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
                ResponseEntity<JSONObject> response = restTemplate.exchange(URL_FIRST + domain + SITE_URL_NOT + pageIndex, HttpMethod.GET, requestEntity, JSONObject.class);
                JSONArray data = Objects.requireNonNull(response.getBody()).getJSONArray("data");
                if (!data.isEmpty()) {
                    siteDtos.addAll(data.toJavaList(SiteDto.class));
                    pageIndex++;
                }else {
                    flag = false;
                }
            }
            return siteDtos;
        } catch (Exception e) {
            log.error("debug getSites ==>" + e.getMessage());
            return null;
        }
    }
}
